package com.chenglu.android.ordercomment;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RatingBar;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chenglu.android.R;
import com.chenglu.android.bean.TabEvent;
import com.chenglu.android.common.base.BaseActionBarActivity;
import com.chenglu.android.common.base.bean.Event;
import com.chenglu.android.common.net.APIService;
import com.chenglu.android.common.net.Constant;
import com.chenglu.android.common.net.RetrofitClientCL;
import com.chenglu.android.common.utils.EventBusUtils;
import com.chenglu.android.common.utils.GlideEngine;
import com.chenglu.android.common.utils.LogUtils;
import com.chenglu.android.common.utils.SPUtils;
import com.chenglu.android.common.utils.ToastUtils;
import com.chenglu.android.common.utils.Utils;
import com.chenglu.android.mine.bean.CommonDataBean;
import com.chenglu.android.mine.bean.PutFileBean;
import com.chenglu.android.order.adapter.AllOrderItemAdapter;
import com.chenglu.android.order.bean.OrderInfoBean;
import com.chenglu.android.ordercomment.adapter.CommentItemAdapter;
import com.chenglu.android.ordercomment.mvp.contract.OrderCommentContract;
import com.chenglu.android.ordercomment.mvp.presenter.OrderCommentPresenter;
import com.chenglu.android.ordercomment.nine.PhotoEvent;
import com.chenglu.android.ordercomment.nine.SelectPlotAdapter;
import com.chenglu.android.ordercomment.nine.Tools;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * @author: lyj
 * @Created: by Copyright 2023 3 Guangzhou Hongma Technology Co., Ltd. All rights reserved.
 * @Description： 订单评论
 */
public class OrderCommentActivity extends BaseActionBarActivity<OrderCommentPresenter> implements OrderCommentContract.View {

    public final static String ORDERNO = "orderno";

    public final static String ORDERLIST = "orderlist";


    String img, orderNo, orderid, orderNumber;
    OrderInfoBean.Data.Records orderlist;

    @BindView(R.id.rv_order_comment)
    RecyclerView rvOrderComment;
    @BindView(R.id.et_order_comment)
    EditText etOrderComment;
    @BindView(R.id.rv_nine_photo)
    RecyclerView rvNinePhoto;
    @BindView(R.id.btn_order_comment)
    Button btnOrderComment;
    @BindView(R.id.cb_comment)
    ImageView cbComment;


    private SelectPlotAdapter adapter;
    private ArrayList<String> allSelectList;//所有的图片集合
    private ArrayList<String> categoryLists;//查看图片集合
    private List<LocalMedia> selectList = new ArrayList<>();
    private String aaccessToken;
    private String content;

    private CommentItemAdapter mItemAdapter;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_order_commment;
    }

    @Override
    protected void initView() {

        setCenterText("订单评论");
        mPresenter = new OrderCommentPresenter();
        mPresenter.attachView(this);


        if (null == allSelectList) {
            allSelectList = new ArrayList();
        }
        if (null == categoryLists) {
            categoryLists = new ArrayList();
        }

        aaccessToken = SPUtils.getString("AaccessToken", "AaccessToken");

        orderNo = getIntent().getStringExtra(ORDERNO);

        orderlist = (OrderInfoBean.Data.Records) getIntent().getSerializableExtra(ORDERLIST);


        initAdapter();

        initcommentAdapter();



    }

    @Override
    protected boolean registerEventBus() {
        return true;
    }

    private void initcommentAdapter() {


        mItemAdapter = new CommentItemAdapter(OrderCommentActivity.this, R.layout.item_order_comment, orderlist.getOrderDetails());

        rvOrderComment.setLayoutManager(new LinearLayoutManager(mContext));
        rvOrderComment.setAdapter(mItemAdapter);
        mItemAdapter.notifyDataSetChanged();

    }

    private void initAdapter() {
        //最多9张图片
        adapter = new SelectPlotAdapter(this, 6);
        rvNinePhoto.setLayoutManager(new GridLayoutManager(this, 3));
        adapter.setImageList(allSelectList);
        rvNinePhoto.setAdapter(adapter);
        adapter.setListener(new SelectPlotAdapter.CallbackListener() {
            @Override
            public void add(int position) {
                //可添加的最大张数=9-当前已选的张数
                int size = 6 - allSelectList.size();
                Tools.galleryPictures(OrderCommentActivity.this, 1, size);

            }

            @Override
            public void delete(int position) {
                allSelectList.remove(position);
                categoryLists.remove(position);
                adapter.setImageList(allSelectList);//再set所有集合
            }

            @Override
            public void item(int position, List<String> mList) {
                selectList.clear();
                for (int i = 0; i < allSelectList.size(); i++) {
                    LocalMedia localMedia = new LocalMedia();
                    localMedia.setPath(allSelectList.get(i));
                    selectList.add(localMedia);
                }
                //①、图片选择器自带预览
                PictureSelector.create(OrderCommentActivity.this)
                        .themeStyle(R.style.picture_default_style)
                        .isNotPreviewDownload(true)//是否显示保存弹框
                        .imageEngine(GlideEngine.createGlideEngine()) // 选择器展示不出图片则添加
                        .openExternalPreview(position, selectList);
                //②:自定义布局预览
                //Tools.startPhotoViewActivity(MainActivity.this, categoryLists, position);
            }
        });
    }


    public List<LocalMedia> mediaList = new ArrayList<>() ;

    public List<LocalMedia> getMediaList() {
        return mediaList;
    }

    public void setMediaList(List<LocalMedia> mediaList) {
        this.mediaList = mediaList;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            // 结果回调
            List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
//            showSelectPic(selectList);
//            for (int i = 0; i <selectList.size() ; i++) {
//                LogUtils.e("e+"+selectList.get(i).getPath());
//                mediaList.add(selectList.get(i));
//            }
            mItemAdapter.showSelectPic(selectList);
            EventBus.getDefault().post(new TabEvent(0));

            mItemAdapter.notifyItemChanged(mItemAdapter.mPhotoPosition);
        }
    }


    private void showSelectPic(List<LocalMedia> result) {
        for (int i = 0; i < result.size(); i++) {
            String path;
            //判断是否10.0以上
            if (Build.VERSION.SDK_INT >= 29) {
                path = result.get(i).getAndroidQToPath();
            } else {
                path = result.get(i).getPath();
            }
            allSelectList.add(path);
            categoryLists.add(path);
            LogUtils.e("图片链接: " + path);
        }
        adapter.setImageList(allSelectList);

    }




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    int picNum = 0;

    ArrayList<String> imgList = new ArrayList<>();

    // 图片的地址 图片的集合 递归去请求数据
    private void upoadImg(String pic, int picSize) {

        if (pic != null) {

            APIService api = RetrofitClientCL.getInstance().getApi();
            File file = new File(pic + "");
            RequestBody requestBody1 = RequestBody.create(MediaType.parse("multipart/form-data"), file);

            MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestBody1);
            Call<PutFileBean> putFileBeanCall = api.uploadImg(aaccessToken, body);
            showLoading();
            putFileBeanCall.enqueue(new Callback<PutFileBean>() {
                @Override
                public void onResponse(Call<PutFileBean> call, Response<PutFileBean> response) {
                    final String json = response.body().toString();
                    LogUtils.e("json" + json);
//                    PutFileBean putFileBean = JSONObject.parseObject(json, PutFileBean.class);
                    imgList.add(response.body().getData().getLink());
                    dismissLoading();
                    picNum++;
                    if (picNum < picSize) {
                        upoadImg(allSelectList.get(picNum), picSize);
                    } else {
                        getAddCheckTire();
                    }

                }

                @Override
                public void onFailure(Call<PutFileBean> call, Throwable t) {
                    dismissLoading();
                    ToastUtils.show("上传失败，请重新上传！");
                    LogUtils.e(t.getMessage());
                }
            });

        }

    }
   private int serveEvaluate;

    //结束递归
    public void getAddCheckTire() {

        for (int i = 0; i < imgList.size(); i++) {
            LogUtils.e("linklist" + imgList.get(i));
        }

        String img = parseListToStr(imgList);

//         "businessReply": "",
//  "goodsId": 0,
//  "goodsName": "",
//  "goodsReview": 0,
//  "goodsSkuId": 0,
//  "goodsSkuSpec": "",
//  "id": 0,
//  "isAnonymity": 0,
//  "isDeleted": 0,
//  "logisticsEvaluate": 0,
//  "orderDetailsId": 0,
//  "reviewCntent": "",
//  "reviewImgList": "",
//  "reviewTime": "",
//  "serveEvaluate": 0,
//  "status": 0,
//  "userId": 0
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("reviewCntent", content);
            jsonObject.put("orderNo", orderNo);
            jsonObject.put("reviewImgList", img);
            jsonObject.put("serveEvaluate", serveEvaluate);


        } catch (Exception e) {
            e.printStackTrace();
        }
        LogUtils.e(new Gson().toJson(jsonObject));
        mPresenter.getOrderComment(aaccessToken, Utils.getRequestBody(jsonObject));
    }


    public static String parseListToStr(List<String> list) {
        StringBuffer sb = new StringBuffer();
        if (list != null) {
            for (int i = 0; i <= list.size() - 1; i++) {
                if (i < list.size() - 1) {
                    sb.append(list.get(i) + ",");
                } else {
                    sb.append(list.get(i));
                }
            }
        }
        return sb.toString();
    }

    @Override
    public void getOrderComment(CommonDataBean bean) {
        //
        if (bean != null) {
            SPUtils.setBoolean(Constant.ISORDERCOMMENT, true);
            finish();
        }


    }


    @Override
    public void getPutFileSuccess(PutFileBean bean) {


    }
     boolean isAnonymity= true;
    @OnClick({R.id.cb_comment, R.id.btn_order_comment})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.cb_comment:
                if(isAnonymity){
                    isAnonymity =false;
                    cbComment.setBackground(getDrawable(R.drawable.icon_comment_press));
                }else {
                    isAnonymity =true;
                    cbComment.setBackground(getDrawable(R.drawable.icon_comment_default));
                }

                break;
            case R.id.btn_order_comment:

                content = etOrderComment.getText().toString();
                if (TextUtils.isEmpty(content)) {
                    ToastUtils.show("请输入上传内容");
                    return;
                }
                if (allSelectList.size() == 0) {
                    //数组转图片
                    getAddCheckTire();

                } else {
                    upoadImg(allSelectList.get(picNum), allSelectList.size());
                }
                break;
        }
    }
}
